<?php

/**
 * 用户中心
 *
 * @package		Hooloo framework
 * @author 		Bill
 * @copyright 	Hooloo Co.,Ltd
 * @version		1.0
 * @release		2017.05.08
 */
//defined('BASEPATH') OR exit('No direct script access allowed');

class User extends Controller{
    public function __construct(){
        parent::__construct();
    }

    /**
     * 基本资料
     */
    public function index() {
        $this->display();
    }
    /*
     * 用户注册
     * @param
     */
    public function register()
    {

        $data = getParam();
        //校验验证码
        $verify = new Verify();
        if (! $verify->check($data['code'], "")) {
                ajax_return(0, '验证码不正确');
        }

        $req=request();
        $tid=substr($req::instance()->param('id'),2,-3);
        $pid=substr($req::instance()->param('pid'),2,-3);
        if($this->request->isPost()){
            $data = $this->request->post();
            $check_code = check_sms_code($data['mobile'], $data['sms_code']);
            //临时关闭验证短信
            true !== $check_code &&  $this->error("验证码错误");
            $result = $this->validate($data, 'Member.create');
            true !== $result  && $this->error($result);
            if(!empty($data['recommend'])) {
                if ($data['recommend'] == $data['mobile']) {
                    $this->error("邀请人不能是自己");
                }
                $r_res = MemberModel::getMemberInfoByMobile($data['recommend']);
                if (empty($r_res)) {
                    $this->error("邀请人不存在");
                }
                $data['agent_far'] = $r_res['id'];//agent_far 生成模拟代理关系
            }
            $data['agent_far'] = isset($data['agent_far'])?$data['agent_far']:$data['agent_far']="";
            $res = MemberModel::saveData($data);
            if(!empty($data['recommend'])){
                $m_res=MemberModel::getMemberInfoByMobile($data['mobile']);
                $data['id']=$m_res['id'];//被邀请人id
                $data['mid']=$r_res['id'];//邀请人id
                $Inv_res=InviteModel::saveData($data);//保存推荐关系数据
            }
            if($res['status']===1){
                $auth = array(
                    'mid'             => $res['data']['id'],
                    'mobile'        => $res['data']['mobile'],
                    'last_login_time' => '',
                    'last_login_ip'   => get_client_ip(1),
                );
                session('member_auth', $auth);
                session('member_auth_sign', data_auth_sign($auth));
            }
            1 === $res['status'] ? 	$this->success($res['message'], URL('/member/index/index')) : $this->error($res['message']);
        }else{
            $mobile="";
            if($tid!==false){
                $tlist=MemberModel::getMemberInfoByID($tid);
                if(!empty($tlist['mobile'])){
                    $mobile=$tlist['mobile'];
                }
            }
            $this->assign('mobile',$mobile);
            $this->assign('pid',$pid);
            return $this->fetch();
        }
    }

    /*
     * 修改手机号
     * */
    public function telephone()
    {
        phpinfo();
        die;
//        $mid=MID;//用户ID
        $info = getParam();
        $mid = isLogin($info['token']);
        $sql = "select account,freeze,operate_account,bond_account from user a left join money b on a.id = b.mid where a.id=$mid";
        $data = $this->db->query($sql)->row_array();
        $old_mobile=$data['mobile'];//旧手机号
        if(!$mid){
            ajaxmsg('登陆后才能操作',0); //判断是否登录获取MID
        }
        $captcha1 = $info['captcha']; //获取手机验证码
        $step = $info['step']; //获取新手机号
        if(empty($step)){$step=1;}
        $new_mobile = $info['mobile']; //获取新手机号
        if($captcha1 && $step==1){  //第一步
            $_SESSION['step_key'] =  'lurenjiayi23101988';
//            $result = $this->validate($captcha1, 'Member.captcha');//验证表单
            $result = true;//验证表单
            if($result){
                if(!check_sms_code($old_mobile,$captcha1)){  //验证手机验证码
                    ajax_return(1,'验证通过,可进入第二部设置');
                }else{
                    ajax_return(0,'验证码错误');
                }
            }else{
                ajax_return(0,'参数错误');
            }
        }elseif($step==2 && !empty($new_mobile)){ //第二步

            $yz = ['mobile'=>$new_mobile];
            // 验证码
            $result1 = true; //验证表单

            if(!empty($result1) && $result1 != true){
                ajax_return(0,'',$result1);
            }else{
                if (!check_sms_code($new_mobile, $captcha1)) {
                    $res = Db::name('member')->where(['id' => $mid])->update(['mobile' => $new_mobile]);
                    if ($res) {
                        $auth = $_SESSION['member_auth'];
                        $auth['mobile'] = $new_mobile;
                        $_SESSION['member_auth'] = $auth;
                        $_SESSION['member_auth_sign'] = data_auth_sign($auth);
                        ajax_return(1,'修改成功');
                    } else {
                        ajax_return(0,'修改失败');
                    }
                }else{
                    ajax_return(0,'验证码错误');
                }
            }
        }
        ajax_return(1,"修改成功");
    }
    /*
     * 短信验证码
     * */
    public function send_sms(){
        $data = getParam();
        /*if (! $data['code']) {
            ajax_return(0, "验证码不能为空");
        }*/

        if (!empty($data['mobile'])){
            $code = rand(1000,9999);
            $_COOKIE['code'] = $code;
            ajax_return(1,'发送成功',$code);
        }else{
            ajax_return(0,'请填写手机号');
        }
    }

    /**
     * 用户登录
     * @param	string	$username	用户名
     * @param	string	$password 	密码
     * @param	string	$verify 	验证码
     * @param	array	$result 	返回结果
     */
    public function login() {
        $data = getParam();
        //执行登录
            //早上8点以前，下午5点以后，周六、周日闭市。
        $h = date("H");
        $w = date("w");
        if (($h < 8 || $h > 17 || $w == 6 || $w == 0)) {
            //系统关闭
            ajax_return(0, '交易系统闭市，暂不开放！');
        }

        //接收参数
        $username = isset($data["username"]) ? substr(sql_format($data["username"]), 0, 20) : "";
        $password = isset($data["password"]) ? $data["password"] : "";
        $code = isset($data["code"]) ? substr($data["code"], 0, 4) : "";

        //校验参数
        if (! $username) {
            ajax_return(0, "用户名不能为空");
        }
        if (! $password) {
            ajax_return(0, "密码不能为空");
        }



        //查找用户
        $sql = "select id, username, sex, nickname, realname, mobile, is_locked, is_stop, is_disable, try_times, last_try, password, atmpwd, demo_account, aid from user where username = '$username'";
        $user = $this->db->query($sql)->row_array();
        if (! $user) {
            ajax_return(0, "您输入的帐号不存在");
        }

        //判断登录次数
        if ($user["try_times"] > 10 && time() - $user["last_try"] < 600) {
            ajax_return(0, "您登录次数太多，请10分钟后重试！");
        }

        //判断密码
        if (DEVELOPMENT_ENVIRONMENT == false && $user["password"] != md5($password)) {
            //更新输错次数
            $sql = "update user set try_times = try_times + 1, last_try = '" . time() . "', ip = '" . get_client_ip() . "' where username = '$username'";
            $this->db->query($sql);
            ajax_return(0, "您输入密码不正确，请重新输入");
        } else {
            //用户是否锁定
            if ($user["is_locked"] == 1) {
                ajax_return(0, "帐号已锁定，禁止访问本网站");
            }
            //用户是否锁定
            if ($user["is_disable"] == 1) {
                ajax_return(0, "帐号已禁用，禁止访问本网站");
            }
            //更新最后登录时间,输错次数为0
            $time = time();
            if (empty($_SESSION['openid']) == false) {
                $field = "openid = '" . $_SESSION['openid'] . "', ";
            } else {
                $field = "";
            }
            $sql = "update user set " . $field . " try_times = 0, last_try = '$time', last_login = '$time', is_online = 1, ip = '" . get_client_ip() . "' where id = '" . $user["id"] . "'";
            $this->db->query($sql);
            $user["last_login"] = $time;
            $token = Jwt::encode($user,JWT_TOKEN_KEY);
            //登录信息入session()
            $_SESSION["user"] = $user;
        }

        //返回登录信息
        ajax_return(1, "登录成功",['token' => $token,'uid' => $_SESSION['user']['id']]);
    }

    /**
     * 验证码
     */
    public function verify(){
        $Verify = new Verify();
        $Verify->fontSize = 14;//文字大小
        $Verify->length   = 4; //验证码字数
        $Verify->useNoise = false;
        $Verify->imageW = 100;//图片宽度
        $Verify->imageH = 28;//图片高度
        $Verify->expire = 600;//时效
        $Verify->entry();
    }

    /**
     * 修改密码
     * @param	string	$oldpassword	旧密码
     * @param	string	$password 		新密码
     * @param	string	$repassword 	确认密码
     */
    public function password() {
        if (IS_POST) {
            //接收参数
            $info = getParam();
            $usr = getUserInfo($info['token']);
            $oldpassword = $info["oldpassword"];
            $password = $info["password"];
            $repassword = $info["repassword"];
            $type = (int)$info["type"];
            $uid = $usr["id"];

            //校验参数
            /*if (! $oldpassword) {
                ajax_return(0, "旧密码不能为空");
            }*/
            if (! $password) {
                ajax_return(0, "新密码不能为空");
            }
            if ($password != $repassword) {
                ajax_return(0, "两次密码不一致");
            }

            //密码类型
            if ($type == 0) {
                //登录密码
                $sql = "select mobile from user where id = $uid";
                $user = $this->db->query($sql)->row_array();
                /*if ($data['code'] != $_COOKIE['code']){
                    ajax_return(0,'您输入的验证码错误');
                }*/
                if ($user['mobile'] == $info['mobile']){
                    /*if ($usr["password"] != md5($oldpassword)) {
                        ajax_return(0, "旧密码不正确");
                    } else {*/
                        $password = md5($password);
                        $sql = "update user set password = '$password' where id = $uid";
                        $res = $this->db->query($sql);
                        if ($res){
                            ajax_return(1,'修改成功');
                        }else{
                            ajax_return(0,'修改失败');
                        }
//                    }
                }else{
                    ajax_return(0,'您输入的手机号错误');
                }
            } else {
                //提款密码
                if ($usr["atmpwd"] != md5($oldpassword)) {
                    ajax_return(0, "旧密码不正确");
                } else {
                    $password = md5($password);
                    $sql = "update user set atmpwd = '$password' where id = $uid";
                }
            }

            //更新密码
            $this->db->query($sql);
            ajax_return(1, "密码修改成功");
        }
    }

    /**
     * 系统公告
     */
    public function common() {
        $sql = "select id, author, title, content, add_time from news where status = 1 and type = 1 order by add_time desc";
        $list = $this->db->query($sql)->result_array();
        ajax_return(1,'',$list);

        /*$this->assign("list", $list);
        $this->display();*/
    }

    /**
     * 短消息
     */
    public function message($start_time = 0, $end_time = 0, $p = 1) {
        //接收参数
        $p = intval($p);
        $uid = $_SESSION["user"]["id"];
        $where = " where receiver = $uid";

        //搜索时间
        if (! $start_time) $start_time = date("Y-m-d");
        if (! $end_time) $end_time = date("Y-m-d");
        if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
        $where .= " and addtime >= '" . $start_time . "' and addtime <= '" . ($end_time . " 23:59:59") . "'";

        //数据分页
        $pize = 15;//每页数量
        if(0 >= $p) $p = 1;
        $start = ($p - 1) * $pize;//分页开始

        //查询总数
        $sql = "select count(*) c from message " . $where;
        $total = $this->db->query($sql)->row_array();
        $total = $total["c"];

        //分页查询
        $sql = "select * from message " . $where . " order by id desc limit $start, $pize";
        $list = $this->db->query($sql)->result_array();

        //分页展示
        $url = "/" . $this->_controller . "/" . $this->_action . "/" . $start_time . "/". $end_time . "/";
        $page = page_format($total, $pize, $p, $url);

        $this->assign("list", $list);
        $this->assign("total", $total);
        $this->assign("page", $page);
        $this->assign("start_time", $start_time);
        $this->assign("end_time", $end_time);
        $this->display();
    }

    /**
     * 读取短消息
     */
    public function read_message() {
        if (IS_POST) {
            $id = isset($_POST["id"]) ? (int)$_POST["id"] : 0;
            if ($id > 0) {
                $uid = $_SESSION["user"]["id"];
                $sql = "update message set isread = 1 where id = $id and isread = 0 and receiver = $uid";
                $this->db->query($sql);
            }

            ajax_return(1, "success");
        }
    }

    /*
     * 用户信息
     * */
    public function userInfo(){
        $info = getParam();
        $mid = isLogin($info['token']);
        $minfo = MemberModel::getMemberInfoByID($mid);
        unset($minfo['passwd']);
        unset($minfo['paywd']);
        if($minfo['id_card'] ==null) $minfo['id_card'] = '';
        if($minfo['name'] ==null) $minfo['name'] = '';
        $minfo['account'] =  bcdiv($minfo['account'],100,2);
        $minfo['freeze'] =  bcdiv($minfo['freeze'],100,2);
        $minfo['operate_account'] =  bcdiv($minfo['operate_account'],100,2);
        $minfo['bond_account'] = bcdiv($minfo['bond_account'],100,2);
        if($minfo['head_img']){
            $saveFile = str_replace("\\",'/',$minfo['head_img']);
            $minfo['head_img'] =  'http://'.$_SERVER['HTTP_HOST'].$saveFile;
        }else{
            $minfo['head_img'] = '';
        }

        $token = array(
            "uid"=>$minfo['id'],
            'doHost'=>$_SERVER['HTTP_HOST'],
            'doTime'=>time(),
            "mobile" => $minfo['mobile'],
        );
        $jwt = Jwt::encode($token, JWT_TOKEN_KEY);
        $minfo['token'] = $jwt;
        ajax_return(1,'用户信息',$minfo);
//        ajaxmsg('用户信息',1,$minfo);
    }

    /**
     * 交易规则
     */
    public function rules() {
        $sql = "select id, author, title, content, add_time from news where status = 1 and type = 3";
        $result = $this->db->query($sql)->row_array();
        $result['content'] = str_replace(PHP_EOL, "<br />", $result['content']);
        $this->assign("result", $result);
        $this->display();
    }

    /**
     * 我的资产
     */
    public function asset() {
        $info = getParam();
        $uid = isLogin($info['token']);
        $result = get_user($uid, 1);
        ajax_return(1, "查询成功", $result);
    }

    /**
     * 退出登录
     */
    public function logout() {
        //删除session
        if (isset($_SESSION["user"])) {
            if (empty($_SESSION['openid']) == false) {
                $field = "openid = '', ";
            } else {
                $field = "";
            }
            //更新在线状态
            $sql = "update user set ".$field." is_online = 0 where id = '" . $_SESSION["user"]["id"] . "'";
            $this->db->query($sql);

            unset($_SESSION["user"]);
        }

        //返回结果集
        ajax_return(1, "退出成功");
//        redirect("/user/login");
    }

    /*
     * 判断用户是否实名
     * */
    public function is_idauth(){
        $data = getParam();
        $usr = getUserInfo($data['token']);
        if (!empty($usr)){
            $uid = $usr["id"];
            $sql = "select id,is_idauth,realname from user where id= $uid";
            $auth = $this->db->query($sql)->row_array();
            ajax_return(1,'',$auth);
        }else{
            ajax_return(0,'用户未登录');
        }
    }
    /*
     * 实名认证
     * */
    public function realname(){
        $info = getParam();
        $user = getUserInfo($info['token']);
        if (isset($user)){
            $id = $user['id'];
            $sql = "select realname,idcard from user where id=" . $id;
            $name = $this->db->query($sql)->row_array();
            if (empty($name['realname'])){
                $check = is_idcard($info['idcard']);
                if ($check && !empty($info['realname'])){
                    $data['realname'] = $info['realname'];
                    $data['idcard'] = $info['idcard'];
                    $sql = "update user set realname = '" . $data['realname'] . "', idcard = '" . $data['idcard'] . "' where id= ".$id;
                    $res = $this->db->query($sql);
                    if ($res){
                        ajax_return(1,'实名提交成功');
                    }else{
                        ajax_return(0,'实名提交失败');
                    }
                }else{
                    ajax_return(0,'身份证信息填写错误');
                }
            }else{
                $sql = "select id,realname,idcard from user where id = " . $id;
                $user = $this->db->query($sql)->row_array();
                ajax_return(0,'用户已实名',$user);
            }
        }else{
            ajax_return(0,'用户未登录');
        }
    }

}
